package com.blb.zy_community.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blb.zy_community.entity.ResponseResult;
import com.blb.zy_community.entity.SysUser;
import com.blb.zy_community.service.ISysUserService;
import com.blb.zy_community.service.impl.SysUserServiceImpl;
import com.blb.zy_community.utils.JwtUtils;
import com.blb.zy_community.utils.RsaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功处理器
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    ISysUserService sysUserService;

    /**
     * 登录成功后的回调方法
     * 参数1 请求 参数2 响应 参数3 验证信息
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //获得登录的用户信息
        User user = (User)authentication.getPrincipal();
        //将用户信息转换为JWTJwtUtils
        String token = JwtUtils.generateToken(user.getUsername(), RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES);
        System.out.println("生成JWT:" + token);
        //通过用户名查询用户对象
//        SysUser sysUserServiceOne = sysUserService.getOne(new QueryWrapper<SysUser>().eq("user_name" ,user.getUsername()));
//        System.out.println(user.getUsername());
//        System.out.println("123416465");
//        SysUser sysUserServiceOne = sysUserService.getSysUserByUserName(user.getUsername());
        //判断状态，如果为0就返回token，如果为1返回禁用
//        if ("0".equals(sysUserServiceOne.getStatus())){
//            //将JWT包装到ResponseResult中转换为json格式=发送json
//        }else {
//            ResponseResult.write(httpServletResponse,ResponseResult.error(403L,"账号已被禁用"));
//        }
        ResponseResult.write(httpServletResponse,ResponseResult.ok(token));


    }
}
